package com.gym.code.generator;

import static com.gym.code.generator.Contants.encoding;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gym.code.generator.model.mapping.BaseGenerateModel;

/**
 * 
 * @author xinchun.wang 
   @email: 532002108@qq.com
 * @createTime 2015-5-23 下午8:47:30 
 * @param <T>
 */
public abstract class AbstractFileGenerator<T extends BaseGenerateModel>  implements Generator<java.lang.Void,T> {
	private final static Logger logger = LoggerFactory.getLogger(AbstractFileGenerator.class);

	private AbstractContentGenerator<T> contentGenerator;
	
	protected AbstractFileGenerator(AbstractContentGenerator<T> contentGenerator){
		this.contentGenerator = contentGenerator;
	}
	
	public final  Void generate(T bean){
		generateFile(bean);
		return null;
	}
	
	
	private  void generateFile(T bean){

		File localFile = new File(bean.getAllPath());
		if(localFile.exists()){
			localFile.delete();
		}
		List<String> lines = contentGenerator.generate(bean);
		try {
			FileUtils.touch(localFile);
		} catch (IOException e) {
			logger.error("touch file error : ",e);
			return;
		}
		try {
			FileUtils.writeLines(localFile, encoding,lines);
		} catch (IOException e) {
			logger.error("write file error : ",e);
		}
	
	}
	
}
